#!/bin/bash

# mongod - Startup script for mongod
SRC_DIR=`dirname $0`
source $SRC_DIR/env.sh

start()
{
  if [ ! -z "`pgrep -f $MONGOD`" ]; then
    echo "mongod already started."
    return 0
  fi
  echo -n $"Starting mongod:"
  $MONGOD -f $CONFIGFILE 1> /dev/null 2>&1
  count=0
  while [ "`$MONGO --quiet localhost:27017/admin -u $ADMIN_ID -p $ADMIN_PASS --eval '1' 2> /dev/null`" != 1 ]; do
    count=`expr $count + 1`
    if [ $count == 300 ]; then
      echo " failed."
      return -1
    fi
    sleep 1
  done
  touch $P_LOCKFILE
  echo " done"
}

stop()
{
  if [ -z "`pgrep -f $MONGOD`" ]; then
    echo "mongod already stopped."
    return 0
  fi
  echo -n $"Stopping mongod:"
  $MONGO localhost:27017/admin -u $ADMIN_ID -p $ADMIN_PASS $SRC_DIR/mongod_shutdown.js 1> /dev/null 2>&1
  count=0
  while [ ! -z "`pgrep -f $MONGOD`" ]; do
    count=`expr $count + 1`
    if [ `expr $count % 10` == 0 ]; then pkill $MONGOD:; fi
    if [ $count == 60 ]; then
      echo " failed."
      return -1
    fi
    sleep 1
  done
  rm -f $P_LOCKFILE
  echo " done"
}

restart () {
  stop
  if [ $? != 0 ]; then
    echo `hostname` | mail -s "failed to stop mongod." "hitoshi.asai@gmo-media.jp"
    return -1
  fi
  start
  if [ $? != 0 ]; then
    echo `hostname` | mail -s "failed to startup mongod." "hitoshi.asai@gmo-media.jp"
    return -1
  fi
}

ulimit -n 12000
RETVAL=0

case "$1" in
  start)
    start
    ;;
  stop)
    stop
    ;;
  restart)
    restart
    ;;
  *)
  echo "Usage: $0 {start|stop|restart}"
esac

RETVAL=$?
exit $RETVAL
